#pragma once

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class Util
{
public:
    static string getOneLine(string &inbuffer, const string &sep)
    {
        auto pos = inbuffer.find(sep);
        if (pos == string::npos)
            return "";

        string sub = inbuffer.substr(0, pos);
        // inbuffer.erase(0, pos + sep.size());

        return sub;
    }

    static bool readFile(const string &resource, string *out)
    {

        ifstream in(resource, ios::binary);
        if (!in.is_open())
            return false; // resource not found

        char buffer[4096];
        while (in.read(buffer, sizeof(buffer)))
        {
            // 仅将实际读取的数据（由 gcount() 返回的大小）追加到输出字符串中
            out->append(buffer, in.gcount());
        }

        // 处理最后一次读取，如果在while循环中因为EOF而结束
        if (in.eof())
        {
            out->append(buffer, in.gcount());
        }
        else if (in.fail())
        {
            in.close();
            return false; // 读取失败
        }

        in.close();
        return true;

        // ifstream in(resource, ios::binary);
        // if(!in.is_open()) return false;     // resource not found

        // char buffer[4096];
        // while(in.read(buffer, sizeof(buffer)))
        // {
        //     *out += buffer;
        // }
        // in.close();
        // return true;
    }

    static string suffixToDesc(const string &suffix)
    {
        string ct = "Content-Type:";
        if (suffix == ".html")
            ct += "text/html";
        else if (suffix == ".jpg")
            ct += "image/jpeg";
        else if (suffix == ".ico")
            ct += "image/svg+xml";

        ct += "\r\n";
        return ct;
    }
};